﻿#region Using Directives

using System;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;

#endregion

namespace GeekRule.ORM
{
    /// <summary>
    /// Microsoft SQL Server IDataContext implementation
    /// </summary>
    public class MsSqlDataContext : IDataContext
    {
        #region Private Members

        private string _contextName = null;
        private DataContextType _contextType = DataContextType.MicrosoftSqlServer;
        private DbConnection _connection = null;
        private DbTransaction _transaction = null;

        #endregion

        #region Constructors

        public MsSqlDataContext()
        {
        }

        /// <summary>
        /// Instantiates MsSqlDataContext and sets up the context connection
        /// </summary>
        /// <param name="connectionStringName"></param>
        public MsSqlDataContext(string connectionStringName)
        {
            string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
            
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ApplicationException("Connection string [" + connectionStringName + "] is was not found");
            }

            _connection = new SqlConnection(connectionString);
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Name for context used to pull specific context's by name when multiple are used
        /// </summary>
        public string ContextName
        {
            get { return _contextName; }
            set { _contextName = value; }
        }

        /// <summary>
        /// Type of data context (e.g. MySql or MicrosoftSqlServer).
        /// Always MicrosoftSqlServer for this class.
        /// </summary>
        public DataContextType ContextType
        {
            get { return _contextType; }
        }

        /// <summary>
        /// Context's Connection
        /// </summary>
        public DbConnection Connection
        {
            get { return _connection; }
            set { _connection = value; }
        }

        /// <summary>
        /// Shared Transaction context
        /// </summary>
        public DbTransaction Transaction
        {
            get { return _transaction; }
            set { _transaction = value; }
        }

        /// <summary>
        /// True if a Transaction is established, false otherwise
        /// </summary>
        public bool HasDbTransaction
        {
            get
            {
                return (_transaction != null);
            }
        }

        #endregion
    }
}
